package com.norra.client.ui

import android.content.Intent
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.*
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.android.material.switchmaterial.SwitchMaterial
import com.norra.base.api.ApiCallback
import com.norra.base.api.HError
import com.norra.base.api.WebService
import com.norra.base.api.entity.*
import com.norra.client.App
import com.norra.client.R
import com.norra.client.model.DeviceEvent
import com.norra.client.viewmodel.DeviceViewModel
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainActivity : BaseActivity() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var viewModel: DeviceViewModel
    private var deviceList = ArrayList<Device>()
    private var isSetting = false
    private var noticeInfo: MsgList.MsgInfo? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        setContentView(R.layout.activity_main)
        val toolbar = findViewById<Toolbar>(R.id.toolbar)
        setSupportActionBar(toolbar)

        val settingIcon = resources.getDrawable(R.drawable.ic_more_vert_24px)
        settingIcon.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
        toolbar.overflowIcon = settingIcon

        recyclerView = findViewById(R.id.recycler_view)
        recyclerView.layoutManager = LinearLayoutManager(this)
        val adapter = CardAdapter()
        recyclerView.adapter = adapter

        findViewById<View>(R.id.btn_add).setOnClickListener {
            startActivity(AddDeviceActivity::class.java)
        }

        findViewById<SwipeRefreshLayout>(R.id.swipe).setOnRefreshListener { loadMyDevice() }

        val addIcon = resources.getDrawable(R.drawable.ic_add_24px)
        addIcon.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
        btn_add.setImageDrawable(addIcon)

        notice_layout.setOnClickListener {
            if (noticeInfo != null) {
                val intent = Intent(this, NoticeActivity::class.java)
                intent.putExtra("info", noticeInfo!!)
                startActivity(intent)
            }
        }
        notice_layout.visibility = View.GONE
        viewModel = ViewModelProvider(this).get(DeviceViewModel::class.java)

        swipe.isRefreshing = true
        loadMyDevice()
        loadNotice()
    }

    private fun setStatus(type: String?, isOpen: Boolean, device: Device, switch: SwitchMaterial) {
        if (isSetting) {
            return
        }
        isSetting = true
        showLoadingView()
        val status = if (isOpen) 1 else 0
        val request = UpdateStatus()
        request.devName = device.devName
        request.status = status
        request.model = type
        WebService.get().setVillaDeviceStatus(request).enqueue(object : ApiCallback<BaseResponse> {
            override fun onSuccess(response: BaseResponse) {
                hideLoadingView()
                isSetting = false
                switch.isChecked = isOpen
                device.status = if (isOpen) arrayOf(1, 1, 1, 1) else arrayOf(0, 0, 0, 0)
            }

            override fun onError(error: HError) {
                hideLoadingView()
                isSetting = false
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onEvent(event: DeviceEvent) {
        when (event.type) {
            DeviceEvent.ADD -> {
                loadMyDevice()
            }
            DeviceEvent.UPDATE -> {
                if (event.device != null) {
                    updateDevice(event.device!!)
                } else {
                    loadMyDevice()
                }
            }

            DeviceEvent.DELETE -> {
                removeDeviceFromList(event.devName)
            }

        }
    }

    private fun updateDevice(device: Device) {
        for (dev in deviceList) {
            if (dev.devId == device.devId) {
                dev.devName = device.devName
                dev.address = device.address
                dev.district = device.district
                dev.models = device.models
                dev.status = device.status
                dev.createOn = device.createOn
                dev.lat = device.lat
                dev.lng = device.lng
                recyclerView.adapter?.notifyDataSetChanged()
                break
            }
        }
    }

    private fun removeDeviceFromList(devName: String?) {
        var dev: Device? = null
        for (device in deviceList) {
            if (devName.equals(device.devName)) {
                dev = device
                break
            }
        }
        if (dev != null) {
            deviceList.remove(dev)
            recyclerView.adapter?.notifyDataSetChanged()
        }
    }


    private fun loadNotice() {
        val request = GetMsgRequest()
        request.num = 1
        request.start = 0
        request.type = 1
        WebService.get().getMsgList(request).enqueue(object : ApiCallback<MsgList> {
            override fun onSuccess(response: MsgList) {
                if (response.isSuccess && response.messages != null && response.messages!!.isNotEmpty()) {
                    noticeInfo = response.messages!![0]
                    updateNotice()
                } else {
                    updateNotice()
                }
            }

            override fun onError(error: HError) {
                updateNotice()
            }
        })
    }

    private fun updateNotice() {
        if (noticeInfo != null) {
            notice_layout.visibility = View.VISIBLE
            notice.text = noticeInfo!!.content
        } else {
            notice_layout.visibility = View.GONE
        }
    }

    private fun loadMyDevice() {
        viewModel.getDeviceList().observe(this, Observer {
            findViewById<SwipeRefreshLayout>(R.id.swipe).isRefreshing = false
            if (it.isSuccess) {
                deviceList.clear()
                if (it.data!!.deviceList != null) {
                    deviceList.addAll(it.data!!.deviceList!!)
                }
                recyclerView.adapter?.notifyDataSetChanged()
            } else {
                //TODO
            }
        })
    }

    override fun onResume() {
        super.onResume()
        recyclerView.adapter?.notifyDataSetChanged()
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.bottom_navigation_menu, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.home) {

        } else if (item.itemId == R.id.logout) {
            App.get().clearUserToken()
            startActivity(LoginActivity::class.java)
            finish()
        }
        return super.onOptionsItemSelected(item)
    }

    private inner class CardAdapter constructor() : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        private var itemTouchHelper: ItemTouchHelper? = null

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val inflater = LayoutInflater.from(parent.context)
            val view: View = inflater.inflate(R.layout.card_list_item, parent, false)
            return CardViewHolder(view)
        }


        override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) {
            (viewHolder as CardViewHolder).bind(deviceList[position], itemTouchHelper)
        }

        override fun getItemCount(): Int {
            return deviceList.size
        }

        private fun setItemTouchHelper(itemTouchHelper: ItemTouchHelper) {
            this.itemTouchHelper = itemTouchHelper
        }

        private inner class CardViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnTouchListener {
            private val titleView: TextView = itemView.findViewById(R.id.device_name)
            private val addressView: TextView = itemView.findViewById(R.id.device_address)
            private val timeView: TextView = itemView.findViewById(R.id.time)
            private val switchMaterial: SwitchMaterial = itemView.findViewById(R.id.switch_row)

            init {
                itemView.setOnClickListener {
                    val intent = Intent(itemView.context, TrashActivity::class.java)
                    intent.putExtra("device", it.tag as Device)
                    itemView.context.startActivity(intent)
                }
            }

            fun bind(device: Device, itemTouchHelper: ItemTouchHelper?) {
                itemView.tag = device
                titleView.text = device.devName ?: ""
                addressView.text = device.address ?: ""
                timeView.text = device.createOn
                switchMaterial.isChecked = device.isNeedClean()
                switchMaterial.tag = device

                switchMaterial.setOnTouchListener(CardViewHolder@ this)
            }

            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                if (v == null || v !is SwitchMaterial) {
                    return true
                }
                val device = v.tag as Device
                if (event!!.actionMasked == MotionEvent.ACTION_UP) {
                    setStatus(null, !v.isChecked, device, v)
                }
                return true
            }
        }

    }


}
